﻿using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using H2.NET.TaskRob;


namespace H2.NET.Web.Pages.SMD
{
    public partial class ChangeDealer : BasePage
    {
        public string step = "";
        public List<string> authidList;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               
                uc_dealer_old.d_title = "原经销商信息";
                uc_dealer_new.d_title = "新经销商信息";
                step = TaskAPI.Step;
                if (ReadOnly()) return;

                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    JsTip(string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser));
                    return;
                }
                btn_submit.Visible = TaskAPI.IsAllowSubmit;
                DwzAssessment1.Category = "ChangeDealer";

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);



                #region Submit Data
                if (TaskAPI.Step == "Submit Data")
                {
                    cb_selected.Enabled = true;
                    // 退回状态，加载数据
                    var dealerId = TaskAPI.GetVariableBySingleValue("BlankVlue");
                    if (!string.IsNullOrEmpty(dealerId))
                    {
                        var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);

                        // 绑定门店列表
                        var stores = StoreService.FindSmdByDealerId(Utils.StrToInt(dealerId, 0));
                        hf_store_count.Value = stores.Count.ToString();
                        cb_depositchange.Checked = storeMasterData.PcModel == "True";
                        rpt_stores.DataSource = stores;
                        rpt_stores.DataBind();

                        // 不能重新选择
                        uc_dealer_old.isCanChoose = false;
                        uc_dealer_old.IsSeeShortName = true;
                       

                        // 隐藏门店列表提示
                        store_list_tip.Visible = false;

                        // 绑定 原经销商、新经销商
                        var changelogs = ChangeLogService.GetLastChangeLogs(assIds);
                        var changelog = changelogs.FirstOrDefault(t => t.FieldName == "DealerID");
                        uc_dealer_old.dealer = DealerService.GetById(Utils.StrToInt(changelog.BeforeValue, 0));
                        uc_dealer_new.dealer = DealerService.GetById(Utils.StrToInt(changelog.AfterValue, 0));

                        // 绑定设备列表
                        var devices = DeviceService.FindNormalDeviceDepositByDealerId(Utils.StrToInt(changelog.BeforeValue, 0));
                        if (devices != null && devices.Count > 0)
                        {

                            tr_devicedeposit_tip.Visible = false;
                            rpt_devicedeposit.DataSource = devices;
                            rpt_devicedeposit.DataBind();
                        }
                    }
                    else
                    {
                        uc_dealer_old.isCanChoose = true;
                        uc_dealer_old.IsSeeShortName = true;
                        
                    }

                    uc_dealer_old.IsCanEditAuthID = false;
                    uc_dealer_old.dealerCallBack = "dealerCallBack";
                    uc_dealer_old.IsSeeShortName = true;
                  

                    uc_dealer_new.IsCanEditAuthID = false;
                    uc_dealer_new.isCanChoose = true;
                    uc_dealer_new.IsSeeShortName = true;
                 

                    if (!String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                    {
                        assessment.Visible = true;

                        var changelogs = ChangeLogService.GetLastChangeLogs(assIds);
                        var changelog = changelogs.FirstOrDefault(t => t.FieldName == "DealerID");
                        var storeIds = changelogs.Select(t => Utils.StrToInt(t.DataID, 0)).ToList();
                        var stores = StoreService.FindSmdByStoreIds(storeIds);

                        authidList = stores.Select(t => t.AuthID).ToList();
                        foreach (var store in stores)
                        {
                            DataHelper<t_smd_Store>.Reload(store, changelogs.Where(t => t.DataID == store.StoreID.ToString()).ToList());
                        }
                        var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                        cb_depositchange.Checked = storeMasterData.PcModel == "True";
                        rpt_stores.DataSource = StoreService.FindSmdByDealerId(Utils.StrToInt(changelog.BeforeValue, 0));
                        rpt_stores.DataBind();

                        uc_dealer_old.dealer = DealerService.GetById(Utils.StrToInt(changelog.BeforeValue, 0));
                        uc_dealer_new.dealer = DealerService.GetById(Utils.StrToInt(changelog.AfterValue, 0));

                        tr_devicedeposit_tip.Visible = false;
                        rpt_devicedeposit.DataSource = DeviceService.FindNormalDeviceDepositByDealerId(Utils.StrToInt(changelog.BeforeValue, 0));
                        rpt_devicedeposit.DataBind();
                    }


                }
                #endregion

                #region 审批环节
                else
                {
                    var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                    if (storeMasterData == null)
                    {
                        btn_submit.Visible = false;
                        JsTip("加载数据失败，请关闭页面重新打开！");
                        return;
                    }
                    hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                    hl_ExportPdf.Visible = true;
                    uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                    store_list_tip.Visible = false;
                    tb_changelogs.Visible = true;

                    uc_change_field1.AssessmentIDs = assIds;
                    uc_change_field1.IsDistinct = false;

                    uc_dealer_old.isCanChoose = false;
                    uc_dealer_old.IsCanEditAuthID = false;
                    uc_dealer_old.IsSeeShortName = true;
                    uc_dealer_new.isCanChoose = false;
                    uc_dealer_new.IsCanEditAuthID = false;
                    uc_dealer_new.IsSeeShortName = true;


                    var changelogs = ChangeLogService.GetLastChangeLogs(assIds);
                    var storeIds = changelogs.Select(t => Utils.StrToInt(t.DataID, 0)).ToList();
                    var stores = StoreService.FindSmdByStoreIds(storeIds);

                    foreach (var store in stores)
                    {
                        DataHelper<t_smd_Store>.Reload(store, changelogs.Where(t => t.DataID == store.StoreID.ToString()).ToList());
                    }

                    if (TaskAPI.Step == "Data Check" || TaskAPI.Step == "Manager Approve")
                    {
                        hf_store_count.Value = stores.Count.ToString();
                        cb_depositchange.Checked = storeMasterData.PcModel == "True";

                        rpt_stores.DataSource = stores;
                        rpt_stores.DataBind();
                    }
                    else
                    {
                        cb_depositchange.Visible = false;
                        cb_depositchange.Checked = storeMasterData.PcModel == "True";
                        l_depositchange.Text = storeMasterData.PcModel == "True" ? "需要发起" : "不需要发起";

                        rpt_stores_readonly.DataSource = stores;
                        rpt_stores_readonly.DataBind();
                    }

                    var changelog = changelogs.FirstOrDefault(t => t.FieldName == "DealerID");
                    uc_dealer_old.dealer = DealerService.GetById(Utils.StrToInt(changelog.BeforeValue, 0));
                    uc_dealer_new.dealer = DealerService.GetById(Utils.StrToInt(changelog.AfterValue, 0));

                    var devices = DeviceService.FindNormalDeviceDepositByStoreIds(storeIds);
                    if (devices != null && devices.Count > 0)
                    {
                        tr_devicedeposit_tip.Visible = false;
                        rpt_devicedeposit.DataSource = devices;
                        rpt_devicedeposit.DataBind();
                    }
                }
                #endregion
            }
        }


        #region 只读表单

        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                assessment.Visible = true;
                btn_submit.Visible = false;
                ajaxUpload1.AllowUpload = false;
                ajaxUpload1.AllowDelete = false;
                DwzAssessment1.Visible = false;

                var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                if (storeMasterData == null)
                {
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }
                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                store_list_tip.Visible = false;
                tb_changelogs.Visible = true;

                var ass = AssessmentService.GetBySubmitData(TaskAPI.Process, TaskAPI.Incident);
                var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
                uc_change_field1.AssessmentIDs = assIds;
                uc_change_field1.IsDistinct = false;

                uc_dealer_old.isCanChoose = false;
                uc_dealer_old.IsCanEditAuthID = false;
                uc_dealer_old.IsSeeShortName = true;
                uc_dealer_new.isCanChoose = false;
                uc_dealer_new.IsCanEditAuthID = false;
                uc_dealer_new.IsSeeShortName = true;

                var changelogs = ChangeLogService.GetLastChangeLogs(assIds);
                var storeIds = changelogs.Select(t => Utils.StrToInt(t.DataID, 0)).ToList();
                var stores = StoreService.FindSmdByStoreIds(storeIds);

                foreach (var store in stores)
                {
                    DataHelper<t_smd_Store>.Reload(store, changelogs.Where(t => t.DataID == store.StoreID.ToString()).ToList());
                }

                cb_depositchange.Visible = false;
                l_depositchange.Text = storeMasterData.PcModel == "True" ? "需要发起" : "不需要发起";

                rpt_stores_readonly.DataSource = stores;
                rpt_stores_readonly.DataBind();

                var changelog = changelogs.Where(t => t.FieldName == "DealerID").FirstOrDefault();
                uc_dealer_old.dealer = DealerService.GetById(Utils.StrToInt(changelog.BeforeValue, 0));
                uc_dealer_new.dealer = DealerService.GetById(Utils.StrToInt(changelog.AfterValue, 0));

                var devices = DeviceService.FindNormalDeviceDepositByStoreIds(storeIds).ToList();
                if (devices != null && devices.Count > 0)
                {
                    tr_devicedeposit_tip.Visible = false;
                    rpt_devicedeposit.DataSource = devices;
                    rpt_devicedeposit.DataBind();
                }

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;

                return true;
            }

            return false;
        }
        #endregion

        private bool Send(ref string return_msg)
        {
            bool flag = false;
            try
            {
                var autoBusinessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                var deviceDeposit = DeviceService.FindNormalDeviceDepositByDealerId(Utils.StrToInt(uc_dealer_old.dealerId, 0));
                #region 数据验证
                if (TaskAPI.Step == "Submit Data" && TaskAPI.IsAllowSubmit && !TaskAPI.Summary.Contains("退回")) // 如果是退回的情况，不存在验证
                {
                    if (uc_dealer_new.code == uc_dealer_old.code)
                    {
                        return_msg = "不能选择相同的经销商";
                        return false;
                    }


                    var stores = new List<int>();
                    var store_count = Utils.StrToInt(hf_store_count.Value, 0);

                    for (var i = 0; i < store_count; i++)
                    {
                        // 过滤没有勾选的门店
                        if (AksRequest.GetFormInt("StoreID" + i) == 0)
                            continue;

                        var id = AksRequest.GetFormInt("ID" + i);
                        stores.Add(id);
                    }
                    if (stores.Count == 0)
                    {
                        return_msg = "请至少勾选一家门店做经销商变更";
                        return false;
                    }
                    var sumAmount = deviceDeposit.Where(t => stores.Contains(t.StoreID)).Sum(t => t.Amount ?? 0);
                    if (sumAmount > 0 && !cb_depositchange.Checked)
                    {
                        return_msg = "若有设备保证金，请勾选需发起保证金变更流程！";
                        return false;
                    }

                    var deviceids = deviceDeposit.Where(t => stores.Contains(t.StoreID)).Select(t => t.DeviceID).ToList<int>();
                    if (DeviceService.IsUnfinish(deviceids) && !TaskAPI.Summary.Contains("退回"))
                    {
                        return_msg = "发现有设备其他业务流程中，请先完成其他流程。";
                        return false;
                    }

                    if (uc_dealer_old.dealer != null)
                    {
                        var _dealercode = uc_dealer_old.code;
                        var _dealer = DealerService.GetByCode(_dealercode);
                        var _devices = DeviceService.FindNormalDeviceDepositByDealerId(_dealer.DealerID);
                        var _stores = StoreService.FindSmdByDealerId(_dealer.DealerID);
                        if (_stores.Count == 0)
                        {
                            JsTip(string.Format("原经销商中没有门店不需要发起经销商变更！"));
                            btn_submit.Visible = false;
                            return false;
                        }
                        foreach (var store in _stores)
                        {
                            var storeContract = ContractService.GetContractByStoreID(store.StoreID);
                            //if (storeContract == null && store.StoreStatus != "关闭" && !store.StoreType.Contains("IS"))
                            if (storeContract == null && store.StoreStatus != "关闭")
                            {
                                t_smd_Contract _contract = new t_smd_Contract();
                                _contract.StoreNature = "无法签署";
                                _contract.StoreID = store.StoreID;
                                _contract.AuthID = store.AuthID;
                                Storage.Save(Storage.Context3, _contract);
                            }
                        }

                        foreach (var device in _devices)
                        {
                            var deviceContract = ContractDeviceService.getContractDeviceByDeviceId(device.DeviceID);
                            if (deviceContract == null && device.Status == "使用")
                            {
                                t_smd_Contract _storeContract = ContractService.GetContractByStoreID(device.StoreID);
                                t_smd_ContractDevice _contractDevice = new t_smd_ContractDevice();
                                _contractDevice.DeviceNature = "无法签署";
                                _contractDevice.DeviceID = device.DeviceID;
                                _contractDevice.DeviceFixAssetNo = device.FullSetSN;
                                _contractDevice.StoreID = _storeContract.StoreID.Value;
                                Storage.Save(Storage.Context3, _contractDevice);
                            }
                        }
                    }

                }
                else if (TaskAPI.Step != "DMO Commit")
                {
                    var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
                    var changelogs = ChangeLogService.GetLastChangeLogs(assIds);
                    var storeIds = changelogs.Select(t => Utils.StrToInt(t.DataID, 0)).ToList();

                    var sumAmount = deviceDeposit.Where(t => storeIds.Contains(t.StoreID)).Sum(t => t.Amount ?? 0);
                    if (sumAmount > 0 && !cb_depositchange.Checked)
                    {
                        return_msg = "若有设备保证金，请勾选需发起保证金变更流程！";
                        return false;
                    }
                }
                if (DwzAssessment1.Assessment.Remark == "")
                {
                    if (DwzAssessment1.Assessment.Opinion == "2")
                    {
                        return_msg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "0")
                    {
                        return_msg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }
                }
                #endregion

                #region 引擎传值
                var summary = "原：" + uc_dealer_old.dealer.Name + "(" + uc_dealer_old.code + "),新：" + uc_dealer_new.dealer.Name + "(" + uc_dealer_new.code + ")";
                if (TaskAPI.Step == "Submit Data")
                {
                    var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    // 空的话，是手动发起的流程
                    TaskAPI["BlankVlue"] = uc_dealer_old.dealerId;
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    TaskAPI.Summary = "经销商变更区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + summary;
                }
                else
                {
                    TaskAPI["ApproveResult"] = DwzAssessment1.Assessment.Opinion;
                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                    if (TaskAPI.Step == "Data Check")
                    {
                        TaskAPI["Checked"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                            TaskAPI.Summary = "经销商变更CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + summary;
                        else if (DwzAssessment1.Assessment.Opinion == "0")
                            TaskAPI.Summary = "(退回)提交经销商变更信息/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + summary;

                    }
                    if (TaskAPI.Step == "Manager Approve")
                    {
                        TaskAPI["Approved"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                            TaskAPI.Summary = "经销商变更DMO导入核查/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + summary;
                        else if (DwzAssessment1.Assessment.Opinion == "0")
                            TaskAPI.Summary = "(退回)经销商变更区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + summary;

                    }
                    else if (TaskAPI.Step == "DMO Commit")
                    {
                        return_msg = "数据更新到主数据库中时出现错误，请跟踪并处理。";
                        TaskAPI["Commited"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "0")
                            TaskAPI.Summary = "(退回)经销商变更CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + summary;
                    }
                }

                #endregion

                #region 提交步骤

                string step = string.Empty;
                Storage.TransactionExecute(o =>
                {
                    #region 业务流程、审批意见记录

                    t_Assessment ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if (lastAss == null || (lastAss != null && lastAss.Step != TaskAPI.Step))
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }

                    #endregion

                    #region “Submit Data”步骤
                    if (TaskAPI.Step == "Submit Data")
                    {
                        var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                        if (storeMasterData == null)
                        {
                            storeMasterData = new t_StoreMasterData();
                            storeMasterData.SubmitDate = DateTime.Now;
                            storeMasterData.Creator = TaskAPI.UserName;
                            storeMasterData.ApplicationNO = uc_head1.applicationNo;
                            storeMasterData.Process = TaskAPI.Process;
                            storeMasterData.Incident = TaskAPI.Incident;

                            storeMasterData.AreaName = TaskAPI.GetVariableBySingleValue("Region");
                            storeMasterData.ProvinceName = TaskAPI.GetVariableBySingleValue("Province");
                            storeMasterData.BusinessProcess = ass.BusinessProcess;
                            storeMasterData.BusinessKey = ass.BusinessKey;
                        }
                        // 不为空，为退回的
                        var dealerID_new = uc_dealer_new.dealerId;
                        var delaerId_old = uc_dealer_old.dealerId;
                        storeMasterData.DealerCode = dealerID_new + "|" + delaerId_old;
                        storeMasterData.PcModel = cb_depositchange.Checked.ToString();

                        // 保存原经销商的设备
                        var dealerId = Utils.StrToInt(uc_dealer_old.dealerId, 0);
                        var devices = DeviceService.FindNormalDeviceDepositByDealerId(dealerId);
                        var deviceIds = devices.Select(t => t.DeviceID).Distinct().ToList();
                        storeMasterData.DispenseModel = string.Join(",", deviceIds);
                        Storage.Save(Storage.Context1, storeMasterData);

                        var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
                        var oldlogs = ChangeLogService.GetLastChangeLogs(assIds);
                        if (oldlogs.Count > 0)
                        {
                            (t_StoreDataChangeLog._LogID.In(ChangeLogService.GetLastChangeLogs(assIds)
                             .Where(t => t.FieldName == "DealerID")
                             .Select(t => t.LogID).ToList())).Delete<t_StoreDataChangeLog>(Storage.Context1);
                        }

                        // 记录变更日志
                        var changelogs = SaveChangeLog(ass.ID);
                        if (changelogs.Count > 0)
                        {
                            Storage.Save(Storage.Context1, changelogs.ToArray());
                        }


                        BusinessService.SaveChildProcess(TaskAPI, ass, "active");
                        var oldDealer = DealerService.GetById(Utils.StrToInt(uc_dealer_old.dealerId, 0));
                        var dealer = DealerService.GetById(Utils.StrToInt(uc_dealer_new.dealerId, 0));
                        var stores = new List<t_smd_Store>();
                        var store_count = Utils.StrToInt(hf_store_count.Value, 0);
                        for (var i = 0; i < store_count; i++)
                        {
                            // 过滤没有勾选的门店
                            if (AksRequest.GetFormInt("StoreID" + i) == 0)
                                continue;

                            var id = AksRequest.GetFormInt("ID" + i);
                            var store = StoreService.GetSmdStoreById(id);
                            stores.Add(store);
                        }
                        var smdDevices = deviceIds.Count == 0 ? null : (t_smd_Device._DeviceID.In(deviceIds)).List<t_smd_Device>(Storage.Context3).ToList();

                        BusinessService.saveProcessRelation(TaskAPI, ass, null, null, dealer, oldDealer, stores, smdDevices, null);
                        var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                        if (key == Constant.PROCESS_CHANGEOTHER && !TaskAPI.Summary.Contains("退回"))
                        {
                            TaskAPI.Summary = "经销商变更区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + " - " + ass.BusinessKey + "|" + summary;
                        }
                    }
                    #endregion

                    #region “Data Check”步骤
                    else if (TaskAPI.Step == "Data Check")
                    {
                        var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                        storeMasterData.PcModel = cb_depositchange.Checked.ToString();
                        Storage.Save(Storage.Context1, storeMasterData);

                        var changelogs = SaveChangeLog(ass.ID);
                        Storage.Save(Storage.Context1, changelogs.ToArray());
                    }
                    #endregion

                    #region “Manager Approve”步骤
                    else if (TaskAPI.Step == "Manager Approve")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                        else
                        {
                            var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                            storeMasterData.PcModel = cb_depositchange.Checked.ToString();
                            Storage.Save(Storage.Context1, storeMasterData);

                            var changelogs = SaveChangeLog(ass.ID);
                            Storage.Save(Storage.Context1, changelogs.ToArray());
                        }
                    }
                    #endregion

                    #region “DMO Commit”步骤
                    else if (TaskAPI.Step == "DMO Commit")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            // 将变更日志转移至smd数据库
                            var smd_changelogs = ChangeLogService.McdToSmd(AssessmentService.GetIdsByTaskApi(TaskAPI));
                            Logging.GetLogger().Info("smd_changelogs success");
                            Storage.Save(Storage.Context3, smd_changelogs.ToArray());
                            Logging.GetLogger().Info(" Save smd_changelogs success");
                            var storeids = smd_changelogs.Select(t => Utils.StrToInt(t.DataID, 0)).Distinct();

                            var stores = StoreService.FindSmdByStoreIds(storeids.ToList());
                            foreach (var storeid in storeids)
                            {
                                var store = stores.FirstOrDefault(t => t.StoreID == storeid);
                                var logs = smd_changelogs.Where(t => t.DataID == storeid.ToString()).ToList();
                                Storage.Save(Storage.Context3, DataHelper<t_smd_Store>.Reload(store, logs));
                                Logging.GetLogger().Info(store.AuthID + " Save success");
                            }

                            // 更新业务数据状态
                            StoreMasterDataService.UpdateFinish(TaskAPI);
                            Logging.GetLogger().Info(" 更新业务数据状态 success");
                            step = "Finish";
                            //新增对businesskey的存储 chris wang
                            var masterStore = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                            BusinessService.SaveSycnMappingAndBusinesskey(3, masterStore.BusinessKey); 
                        }
                        else if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                    }
                    #endregion
                });
                if (DwzAssessment1.Assessment.Opinion != "2")
                {
                    // 变更列表
                    TaskAPI["Content"] = ChangeLogService.GenerateExcel(TaskAPI);
                    TaskAPI["Alert"] = "根据系统匹配，此经销商已经与我们公司停止合作，新的经销商编号为：" + uc_dealer_new.code + "，请与销售确认后进入主数据系统进行修改。";
                    flag = TaskAPI.Send();
                }
                //如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                if (TaskAPI.Step == "Submit Data")
                {
                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 &
                     t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                     {
                         p.Incident = TaskAPI.Incident;
                     });

                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 &
                     t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                     {
                         p.Incident = TaskAPI.Incident;
                     });
                }
                else
                {
                    if (step == "Finish")
                    {
                        var needContract = true;
                        BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                        var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                        Logging.GetLogger().Info("AutoBusinessKey:" + autoBusinessKey);
                        if (!string.IsNullOrEmpty(autoBusinessKey) && autoBusinessKey == Constant.PROCESS_CHANGEDEALER)
                        {
                            var region = TaskAPI.GetVariableBySingleValue("Region").ToUpper();
                            var province = TaskAPI.GetVariableBySingleValue("Province");

                            var dealerId = uc_dealer_new.dealerId;
                            var delaerId_old = uc_dealer_old.dealerId;
                            storeMasterData.DealerCode = dealerId + "|" + delaerId_old;
                            Storage.Save(storeMasterData);
                            var smd_changelogs = ChangeLogService.McdToSmd(AssessmentService.GetIdsByTaskApi(TaskAPI));
                            var storeids = smd_changelogs.Select(t => Utils.StrToInt(t.DataID, 0)).Distinct();
                            var stores = StoreService.FindSmdByStoreIds(storeids.ToList());
                            Logging.GetLogger().Info("门店数量：" + stores.Count);
                            Logging.GetLogger().Info("准备发起流程");
                            if (storeMasterData.PcModel == "True")
                            {
                                Logging.GetLogger().Info("准备发起保证金");

                                #region 发起保证金变更流程

                                var taskAPI = new TaskAPI(TaskHelper.STORE_DEPOSIT_CHANGE_TASKID);
                                var applicationNo = GenerateApplicationNo(taskAPI);
                                taskAPI["ParentProcess"] = TaskAPI.Process;
                                taskAPI["ParentIncident"] = TaskAPI.Incident;
                                taskAPI["AutoBusinessKey"] = autoBusinessKey;
                                // 新经销商|旧经销商
                                taskAPI["BlankVlue"] = dealerId + "|" + delaerId_old;
                                taskAPI["Region"] = region;
                                taskAPI["Province"] = province;
                                taskAPI.InitAutoTask(applicationNo);
                                taskAPI.Summary = "设备保证金变 / " + TaskHelper.getSummary(TaskAPI.Summary) + "-" + summary;
                                ;
                                taskAPI.SetDepositChangeRecipient(region, province);
                                Logging.GetLogger().Info("准备send发起保证金");
                                if (taskAPI.Send())
                                {
                                    Logging.GetLogger().Info("准备send发起保证金成功");
                                    var ass = taskAPI.InitAutoAssessment();

                                    Storage.Save(Storage.Context1, ass);

                                    BusinessService.SaveChildProcess(taskAPI, ass, "active");
                                }
                                else
                                {
                                    Logging.GetLogger().Info("准备send保证金失败");
                                }

                                #endregion
                            }

                            if (stores.Count > 0)
                            {
                                if (stores.All(t => t.StoreType.Contains("IS")))
                                {
                                    if ((t_smd_Device._StoreID.In(stores.Select(t => t.StoreID).ToList()))
                                            .List<t_smd_Device>(Storage.Context3).Count == 0)
                                    {
                                        needContract = false;
                                    }
                                }
                            }


                            var devicesIsNull = false;  //20170111 Add 是否有设备,有设备才发起合同变更
                            if (needContract)
                            {
                                var devicesList = DeviceService.FindNormalDeviceDepositByStoreIds(storeids.ToList());
                                //20170111 Add 有设备且有设备状态不为报废时才发起合同变更
                                if (devicesList.Count > 0)
                                {
                                    devicesIsNull = true;
                                }
                                if (devicesIsNull)
                                {
                                    Logging.GetLogger().Info("准备发起合同");
                                    var _storeids = stores.Where(t => !t.StoreType.Contains("IS")).Select(store => Convert.ToInt32(store.StoreID)).Distinct().ToList();
                                    var isStore = stores.Where(t => t.StoreType.Contains("IS"));
                                    if (isStore.Any())
                                    {
                                        var _devices =
                                            (t_smd_Device._StoreID.In(
                                                stores.Where(t => t.StoreType.Contains("IS"))
                                                    .Select(store => store.StoreID)
                                                    .ToList())).List<t_smd_Device>(Storage.Context3);
                                        if (_devices.Count > 0)
                                        {
                                            var deviceSids = _devices.Select(d => Convert.ToInt32(d.StoreID)).Distinct().ToList();
                                            _storeids = _storeids.Union(deviceSids).Distinct().ToList<int>();
                                        }
                                    }

                                    #region 发起合同变更流程
                                    var taskAPI = new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID);
                                    var applicationNo = GenerateApplicationNo(taskAPI);

                                    taskAPI["ParentProcess"] = TaskAPI.Process;
                                    taskAPI["ParentIncident"] = TaskAPI.Incident;
                                    taskAPI["AutoBusinessKey"] = autoBusinessKey;
                                    //taskAPI["BlankVlue"] = string.Join("|",  devicesList.Select(d => Convert.ToInt32(d.StoreID)).Distinct().ToList());//_storeids 20170111 update 没显示在设备列表的也不显示在合同子流程中
                                    taskAPI["BlankVlue"] = string.Join("|", _storeids);
                                    taskAPI["Actions"] = "BatchContract";
                                    taskAPI["Region"] = region;
                                    taskAPI["Province"] = province;
                                    taskAPI.InitAutoTask(applicationNo);
                                    taskAPI.Summary = "门店合同信息变更 / " + TaskHelper.getSummary(TaskAPI.Summary) + "-" + summary; ;
                                    taskAPI["Alert"] = "此门店需要进行签署以下合同，请通知相关人员签署合同并提交总部：\n\r" +
                                                       "1. 合同终止及三方转移合同\r\n" +
                                                       "2. 多乐士专卖店店铺协议\r\n" +
                                                       "3. 调色机发放协议---标准购机旧机投放---STD-Transfer-1401A";

                                    taskAPI["MailSubject"] = string.Format("授权号：{0} -- {1}）", stores[0].AuthID, stores[0].StoreType);

                                    taskAPI.SetStoreDataChangeRecipient(region, province, "Contract");
                                    Logging.GetLogger().Info("准备send合同");
                                    if (taskAPI.Send())
                                    {
                                        Logging.GetLogger().Info("准备send合同成功");
                                        var ass = taskAPI.InitAutoAssessment();
                                        Storage.Save(Storage.Context1, ass);
                                        BusinessService.SaveChildProcess(taskAPI, ass, "active");
                                    }
                                    else
                                    {
                                        Logging.GetLogger().Info("准备send合同失败");
                                    }

                                    foreach (var store in stores)
                                    {
                                        #region 签终止协议。
                                        var contract = ContractService.GetContractByStoreID(store.StoreID) ?? new t_smd_Contract
                                        {
                                            AuthID = store.AuthID,
                                            StoreID = store.StoreID

                                        };
                                        // 2016-11-20 update 取消门店合同及门店终止合同
                                        //if (store.StoreType == "DCSS" || store.StoreType == "DDCN")
                                        //{
                                        //    var contractCancel = ContractService.GetContractCancel(contract);
                                        //    var oldContract = ContractService.GetOldContract(contract);
                                        //    oldContract.StoreCancelContractType = contract.StoreContractType;
                                        //    Storage.Save(Storage.Context3, oldContract);
                                        //    Storage.Save(Storage.Context3, contractCancel);
                                        //    contract = ContractService.GetNewContract(contract, false,store.StoreType);
                                        //    Storage.Save(Storage.Context3, contract);
                                        //}
                                        #endregion

                                        #region 签设备终止协议
                                        
                                        //var devices2 = (t_smd_Device._StoreID == store.StoreID & t_smd_Device._Status != "报废" & t_smd_Device._Status != "无设备").List<t_smd_Device>(Storage.Context3);  //20170112

                                        var devices = (t_smd_Device._StoreID == store.StoreID).List<t_smd_Device>(Storage.Context3); 

                                        if (devices != null)
                                        {
                                            foreach (var device in devices)
                                            {
                                                var deviceContract = ContractDeviceService.getContractDeviceByDeviceId(device.DeviceID) ?? new t_smd_ContractDevice { DeviceID = device.DeviceID };
                                                var deviceContractCancel = ContractDeviceService.GetContractDeviceCancel(deviceContract);
                                                var deviceContractOld = ContractDeviceService.GetOldContractDevice(ContractDeviceService.getContractDeviceByDeviceId(device.DeviceID) ?? new t_smd_ContractDevice { DeviceID = device.DeviceID });
                                                if (deviceContractOld != null)
                                                {
                                                    deviceContractOld.DeviceCancelContractType =
                                                        ContractDeviceService.getContractDeviceByDeviceId(device.DeviceID) == null ? "" : ContractDeviceService.getContractDeviceByDeviceId(device.DeviceID).DeviceContractType;
                                                    Storage.Save(Storage.Context3, deviceContractOld);
                                                }
                                                Storage.Save(Storage.Context3, deviceContractCancel);
                                                deviceContract.StoreID = contract.StoreID.Value;
                                                deviceContract = ContractDeviceService.GetNewContract(deviceContract, device.DeliveryType);
                                                Storage.Save(Storage.Context3, deviceContract);
                                            }
                                        }
                                        #endregion
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Logging.GetLogger().Error("调用ChangeDealer.aspx方法Send_Click出错：" + ex);
                flag = false;
            }
            return flag;
        }

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            string return_msg = string.Empty;
            if (Send(ref return_msg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { closeWin(); } });", true);
                return;
            }
            else
            {
                return_msg = return_msg ?? Resources.Global.C_00_Failed;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.prompt('" + return_msg + "','提示', 'info');", true);
                return;
            }
        }

        private List<t_StoreDataChangeLog> SaveChangeLog(string assid)
        {
            // 读取变更日志
            var existing_changelogs = ChangeLogService.GetLastChangeLogs(TaskAPI);

            var changelogs = new List<t_StoreDataChangeLog>();

            var store_count = Utils.StrToInt(hf_store_count.Value, 0);
            for (var i = 0; i < store_count; i++)
            {
                // 过滤没有勾选的门店
                if (AksRequest.GetFormInt("StoreID" + i) == 0)
                    continue;

                var id = AksRequest.GetFormInt("ID" + i);
                var storeName = AksRequest.GetFormString("StoreName" + i);
                var contractPerson = AksRequest.GetFormString("ContractPerson" + i);
                var telephone = AksRequest.GetFormString("Telephone" + i);
                var address = AksRequest.GetFormString("Address" + i);

                var store = StoreService.GetSmdStoreById(id);
                if (store == null) store = new t_smd_Store();
                DataHelper<t_smd_Store>.Reload(store, existing_changelogs.Where(t => t.DataID == id.ToString()).ToList());

                t_smd_Store new_store = (t_smd_Store)store.CloneObject();
                new_store.StoreName = storeName;
                new_store.ContactPerson = contractPerson;
                new_store.PhoneNumber = telephone;
                new_store.StoreAddress = address;
                new_store.DealerID = Utils.StrToInt(uc_dealer_new.dealerId, 0);

                changelogs.AddRange(DataHelper<t_smd_Store>.GetChangeLogs(store, new_store,
                    new_store.GetChangeFields(), "StoreID", UserAPI.UserFullName, assid, "ChangeDealer"));
            }

            return ChangeLogService.GetDistinctChangeLogs(changelogs, existing_changelogs);
        }

        protected void rpt_stores_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
        {
            var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
            var changelogs = ChangeLogService.GetLastChangeLogs(assIds);
            var storeIds = changelogs.Select(t => Utils.StrToInt(t.DataID, 0)).ToList();
            var stores = StoreService.FindSmdByStoreIds(storeIds);
            authidList = stores.Select(t => t.AuthID).ToList();

            var storeid = e.Item.FindControl("storeid") as HtmlInputHidden;
            var authidcode = e.Item.FindControl("authidcode") as HtmlInputHidden;
            var check = e.Item.FindControl("authidCheck") as HtmlInputCheckBox;
            check.Attributes.Add("value", storeid.Value);
            check.Attributes.Add("authid", authidcode.Value);
            check.Checked = TaskAPI.Step != "Submit Data" || (authidList.Contains(authidcode.Value) ? true : false);
            check.Attributes.Add("disabled", TaskAPI.Step == "Submit Data" ? "" : "disabled");
        }

        protected void rpt_devicedeposit_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
        {
            var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
            var changelogs = ChangeLogService.GetLastChangeLogs(assIds);
            var storeIds = changelogs.Select(t => Utils.StrToInt(t.DataID, 0)).ToList();
            var stores = StoreService.FindSmdByStoreIds(storeIds);
            authidList = stores.Select(t => t.AuthID).ToList();

            var tr = e.Item.FindControl("deviceTr") as HtmlTableRow;
            var authid = e.Item.FindControl("d_authid") as HtmlInputHidden;

            tr.Attributes.Add("class", "authid");
            tr.Attributes.Add("authid", authid.Value);
            if (!authidList.Contains(authid.Value))
            {
                tr.Style.Add("display", "none");
            }


        }



    }
}